const {

    ad,
    statistics,
    hottoplist,
    hotlist,
    hotMerchants,
    merchantsType,
    messageType,
    addtype,
    recotribelist,
    tribetopiclist,
    ordercount,
    collectioncount,
    messageunread,
    bulletinlist,
} = require('../../utils/api')

const {
    fetch,
    newFetch
} = require('../../utils/fetch')

const {
    formatNum
} = require('../../utils/utils')
const {
    MYLIST
} = require('../../utils/data')
const app = getApp()

Page({
    data: {
        userInfo: app.globalData.userInfo,
        currentAddress: app.globalData.currentAddress,
        selarea: app.globalData.selarea,
        activeUrl: 'index',
        actionsShow: false,
        actions: [{
                name: '商业信息',
                index: 1
            },
            {
                name: '便民信息',
                index: 0
            },
            {
                name: '广告投放',
                index: 2
            }
        ],
        // actionsTcShow: false,

        swiperList: [],
        swiperList1: [],
        messageTypeList: [],
        merchantsTypeList: [],
        MYLIST: MYLIST,
        statisticsList: [],
        statisticsList1: [],
        hottoplist: [], //置顶列表
        hotlist: [],
        merchantsList: [],
        // recotribelist: [],
        tribetopiclist: [],
        tabbarConf: {
            index: {
                loaded: true,
                num: 1,
                moreFlag: true,
                hasMore: true
            },
            merchants: {
                loaded: false,
                num: 1,
                moreFlag: true,
                hasMore: true
            },
            interactive: {
                loaded: false,
                num: 1,
                moreFlag: true,
                hasMore: true
            },
            my: {
                loaded: false,
                num: 1,
                moreFlag: true,
                hasMore: true
            }
        },
        keyWord: '',
        myorder: 0,
        mycollection: 0,
        selectArray: [{
            "id": "1",
            "text": "搜索部落"
        }, {
            "id": "2",
            "text": "搜索话题"
        }],
        mescount: 0,
        announcementlist: [], //公告数据
        specificarea: null,
        wodecount: 0
    },
    onLoad: function (op) {

        // console.log(app.globalData.userInfo, '哈哈哈')
        var that = this;
        if (op.interactive) {
            if(op.interactive=='my') {
                this.mydatalist()
            }
            this.setData({
                activeUrl: op.interactive
            })
        }
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#ea9518'
        })
        if (op.selarea) {
            var selobj = JSON.parse(op.selarea)
            this.setData({
                selarea: selobj
            })
        } else {
            if (wx.getStorageSync('selarea')) {
                this.setData({
                    selarea: wx.getStorageSync('selarea')
                });
            } else {
                this.setData({
                    selarea: app.globalData.selarea
                });
            }
        }
        //   console.log('进入主页index.js show():selarea:', wx.getStorageSync('selarea'), this.data.selarea);

        if (this.data.selarea && this.data.selarea.adcode) {
            this.setData({
                specificarea: this.data.selarea.adcode,
            })
        } else {
            if (!wx.getStorageSync('currentAddress')) {
                this.setData({
                    specificarea: 110105
                })
            } else {
                this.setData({
                    specificarea: wx.getStorageSync('currentAddress').ad_info.adcode
                })
            }
        }
        wx.setStorage({
            data: this.data.specificarea,
            key: 'specificarea',
        })
        this.getInitData()


       

        if (app.globalData.currentAddress) {
            this.setData({
                currentAddress: app.globalData.currentAddress
            })
        } else {
            app.LocaInfoReadyCallback = res => {
                this.setData({
                    currentAddress: res
                })
            }
        }

        /*
        app.setWatching('currentAddress', currentAddress => {
            this.setData({
                currentAddress
            })
        })
        app.setWatching('userInfo', userInfo => {
            this.setData({
                userInfo
            })
        })*/

        this[this.data.activeUrl + 'GetInitData']()

    },
    onShow: function () {
        // this.setData({
        //     actionsTcShow: false
        // });
        let {
            activeUrl
        } = this.data
        // wx.showNavigationBarLoading()
        let tabbarConf = this.data.tabbarConf
        tabbarConf[activeUrl].num = 1
        this.setData({
            tabbarConf
        })

        this.interactiveGetInitData()

        // this[activeUrl + 'GetInitData']()
    },

    onShareAppMessage: function (res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
        }
        return {
            title: '信息分类小程序',
            path: '/pages/index/index',
            success: function (res) {
                // 转发成功
            },
            fail: function (res) {
                // 转发失败
            }
        }
    },

    onShareTimeline: function (res) {
        return {
            title: '信息分类小程序',
            query: {
                key: value
            },
            imageUrl: ''
        }
    },
    // 因为自定义了tabbar，所以四个一级页面初始化数据需要在一下四个方法里面分别获取
    getInitData() {
        // 首页广告轮播
        // ad({ typeid: 1 }).then(res => {
        //     this.setData({
        //         swiperList: res
        //     })
        // })
        let {
            specificarea
        } = this.data
        fetch(`wx/ad/${specificarea}/list`, 'POST', {
            typeid: 1
        }).then(res => {
            this.setData({
                swiperList: res
            })
        })

        // 首页分类icon信息
        fetch(`wx/message/${specificarea}/type`, 'POST').then(res => {
            let data = res.map(item => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg,
                    path: '/pages/indexList/index',
                    data: item
                })
            })
            app.globalData.messageTypeList = data
            this.setData({
                messageTypeList: data
            })
        })
        // 公告中心界面
        fetch(`wx/info/${specificarea}/bulletin`, 'POST', {
            typeid: 3
        }).then(res => {
            if (res) {
                this.setData({
                    announcementlist: res.list
                })
            }
        })
        // 首页信息浏览量
        fetch(`wx/area/${specificarea}/info`, 'POST', {
            typeid: 1
        }).then(res => {
            if (!res) {
                res = {
                    message_readnum: 0,
                    message_shouReadnum: 0,
                    message_fabunum: 0,
                    message_shouFabunum: 0,
                }
            }

            let statisticsList = [{
                    text: '信息浏览量',
                    num: formatNum(
                        res.message_readnum + res.message_shouReadnum
                    )
                },
                {
                    text: '发布信息',
                    num: formatNum(
                        res.message_fabunum + res.message_shouFabunum
                    )
                }
            ]

            this.setData({
                statisticsList
            })
        })
        // 首页置顶付费
        this.indextoplist()
        this.indexGetInitData()
        // 商户页面广告
        fetch(`wx/ad/${specificarea}/list`, 'POST', {
            typeid: 2
        }).then(res => {
            app.globalData.swiperList1 = res
            this.setData({
                swiperList1: res
            })
        })
        // 商户页面浏览信息
        fetch(`wx/area/${specificarea}/info`, 'POST', {
            typeid: 2
        }).then(res => {
            if (!res) {
                res = {
                    message_readnum: 0,
                    message_shouReadnum: 0,
                    message_shouFabunum: 0,
                    // message_shouFabunum:0
                }
            }

            let statisticsList1 = [{
                    text: '信息浏览量',
                    num: formatNum(
                        res.message_readnum + res.message_shouReadnum
                    )
                },
                {
                    text: '发布信息',
                    num: formatNum(
                        res.message_fabunum + res.message_shouFabunum
                    )
                }
            ]
            this.setData({
                statisticsList1
            })
        })
        fetch(`wx/store/${specificarea}/type`, 'POST').then(res => {
            let data = res.map((item, index) => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg,
                    path: `/pages/merchantsList/index`,
                    data: item
                })
            })
            app.globalData.merchantsTypeList = data
            this.setData({
                merchantsTypeList: data
            })
        })

        fetch(`wx/message/${specificarea}/type`, 'POST').then(res => {
            let data = res.map(item => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg
                })
            })
            app.globalData.addtype = data
        })
    },
    mydatalist() {
        let {
            specificarea
        } = this.data
        // 我的消息提示
     newFetch(`wx/message/${this.data.specificarea}/hasNoRead`, 'POST', {
      memberId: wx.getStorageSync('userInfo').id
  }).then(res => {
      this.setData({
          wodecount: res
      })
  })

        // 我的订单数量  memberId
        newFetch(`wx/order/${specificarea}/count`, 'POST', {
            memberId: wx.getStorageSync('userInfo').id
        }).then(res => {
            if (res.code == 200) {
                this.setData({
                    myorder: res.data.count
                })
            }
        })
        // 消息提示
        newFetch(`wx/message/${specificarea}/isHasMessage`, 'POST', {
            // memberId: 140
            memberId: wx.getStorageSync('userInfo').id
        }).then(res => {
            this.setData({
                mescount: res
            })
        })
        // 我的收藏数量
        newFetch(`wx/collect/${specificarea}/collectcount`, 'POST', {
                memberId: wx.getStorageSync('userInfo').id
            }).then(res => {
                if (res.code == 200) {
                    this.setData({
                        mycollection: res.data.count
                    })
                }
            })
    },
    // 首页置顶付费
    indextoplist() {
        fetch(`wx/message/${this.data.specificarea}/toplist`, 'POST').then(res => {
            if (res) {
                this.setData({
                    hottoplist: res.toplist
                })
            }
        })
    },
    indexGetInitData() {
        // 首页列表
        newFetch(`wx/message/${this.data.specificarea}/hotlist`, 'POST', {
            pageNumber: this.data.tabbarConf.index.num,
        }).then(res => {
            if (this.data.tabbarConf.index.num == 1) {
                this.setData({
                    hotlist: []
                })
            }
            this.setData({
                hotlist: this.data.hotlist.concat(res.data.list)
            })
            // if (obj !== object) {
            //   tabbarConf[obj.url].hasMore = false
            // } 

        //    let  arrMap = this.data.hotlist.map(val=>{
        //         val.details = val.details.split('&amp;hc').join(' ');
        //     return  val
        //         console.log(val, '施蒂利克发及时来电看房就')
        //     })
        //     console.log(arrMap, 'lsdkj删掉了看见')
        //     console.log(this.data.hotlist, 'dslkj')

            this.stopRefreshFn({
                url: 'index',
                list: this.data.hotlist,
                pageCount: res.data.pageCount
            })
        })
    },
    merchantsGetInitData() {
        newFetch(`wx/store/${this.data.specificarea}/hotlist`, 'POST').then(res => {
            if (this.data.tabbarConf.merchants.num == 1) {
                this.setData({
                    merchantsList: []
                })
            }
            if (res.data == null) {
                this.stopRefreshFn({
                    url: 'merchants',
                    list: this.data.merchantsList,
                    pageCount: 1
                })
            } else {
                this.setData({
                    merchantsList: this.data.merchantsList.concat(res.data.list)
                })
                this.stopRefreshFn({
                    url: 'merchants',
                    list: this.data.merchantsList,
                    pageCount: res.data.pageCount
                })
            }
        })
    },
    interactiveGetInitData() {
        // fetch(`wx/tribe/${this.data.specificarea}/recotribelist`, 'POST').then(res => {
        //     this.setData({
        //         recotribelist: res.splice(0, 4)
        //     })
        // })
        newFetch(`wx/tribe/${this.data.specificarea}/tribetopiclist`, 'POST').then(res => {
            if (res.data.length == 0) {
                this.stopRefreshFn({
                    url: 'interactive',
                    list: res.data,
                    pageCount: 1
                })
                return
            }
            this.stopRefreshFn({
                url: 'interactive',
                list: res.data,
                pageCount: 1
            })
            if (this.data.tabbarConf.interactive.num == 1) {
                this.setData({
                    tribetopiclist: []
                })
            }
            res.data.map(val=>{
                val.photohead = val.photohead ? val.photohead.split(',') : val.photohead
            })
            this.setData({
                tribetopiclist: this.data.tribetopiclist.concat(res.data)
            })
        })
    },

    // 搜索
    goSearch: function () {
        wx.navigateTo({
            url: '/pages/homepagesearch/index?searchpage=' + 'index',
        })
    },
    goIndexadver: function () {
        if (!wx.getStorageSync('userInfo')) {
            wx.reLaunch({
                url: '/pages/login/index'
            })
            return;
        }
        wx.navigateTo({
            url: '/pages/publishad/index',
        })
    },
    // 搜索商户
    gomerSearch: function () {
        wx.navigateTo({
            url: '/pages/homepagesearch/index?searchpage=' + 'merchants',
        })
    },
    // 我的订单列表
    goOrder: function () {
        wx.navigateTo({
            url: '/pages/myorderpage/index?orderpage=' + 'order',
        })
    },
    // 我的收藏列表
    goCollection: function () {
        wx.navigateTo({
            url: '/pages/myorderpage/index?orderpage=' + 'collection',
        })
    },
    myGetInitData(obj) {
        this.stopRefreshFn({
            url: 'my'
        })
    },
    actionsShowFn: function () {
        this.setData({
            actionsShow: !this.data.actionsShow
        })
    },
    tabbarTCClick: function () {
        // this.setData({
        //     actionsTcShow: !this.data.actionsTcShow
        // })
       
        // wx.navigateTo({
        //   url: '/pages/topicDetails/index',
        // })
        wx.navigateTo({
          url: '/pages/release/release',
        })
    },
    tabbarClick: function (e) {
        let {
            url,
            title
        } = e.currentTarget.dataset
        if (url === this.data.activeUrl) {
            return false
        }
        if (url === 'publishedIn') {
            this.actionsShowFn()
        } else {
            if (!this.data.tabbarConf[url].loaded) {
                this[url + 'GetInitData']()
            }
            var backgroundColor = '#ea9518'
            switch (url) {
                case 'index':
                    wx.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#ea9518'
                    })
                    break
                case 'my':
                    if (!wx.getStorageSync('userInfo')) {
                        wx.reLaunch({
                            url: '/pages/login/index'
                        })
                    } else {
                        this.mydatalist()
                    }
                    wx.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#ea9518'
                    })
                    break
                default:
                    wx.setNavigationBarColor({
                        frontColor: '#000000',
                        backgroundColor: '#fff'
                    })
                    break
            }
            let tabbarConf = this.data.tabbarConf
            tabbarConf[url].loaded = true
            this.setData({
                activeUrl: url,
                tabbarConf
            })

            wx.setNavigationBarTitle({
                title
            })
        }
    },
    onCloseTC() {
        // this.tabbarTCClick()
    },
    onClose() {
        this.actionsShowFn()
    },

    onSelect(e) {
        let {
            index
        } = e.detail
        if (index === 0) {
            wx.navigateTo({
                url: '/pages/lawhall/index'
            })
        }
        if (index === 1) {
            if (!wx.getStorageSync('userInfo')) {
                wx.reLaunch({
                    url: '/pages/login/index'
                })
                return;
            }
            wx.navigateTo({
                url: '/pages/publishlist/index?index=0'
            })
        }
        if (index === 2) {
            if (!wx.getStorageSync('userInfo')) {
                wx.reLaunch({
                    url: '/pages/login/index'
                })
                return;
            }
            wx.navigateTo({
                url: '/pages/publishad/index',
            })
        }
    },
    jumpToTenants() {
        wx.navigateTo({
            url: '/pages/lawhall/index?type=tenants'
        })
    },
    recotribeDetail() {
        // 部落详情
    },
    // 话题详情
    topicDetails(e) {
        let {
            id
        } = e.currentTarget.dataset
        // wx.navigateTo({
        //     url: `/pages/topicDetails/index?id=${id}`
        // })
        wx.navigateTo({
           url: `/pages/tongdetail/index?id=${id}`,
        })
        
    },
    // recotribeMore() {
    //     // 更多部落
    //     wx.navigateTo({
    //         url: '/pages/tribalList/index'
    //     })
    // },
    recotribeTopicList(e) {
        //列表
        let {
            id
        } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/topicList/index?id=${id}`
        })
    },
    stopRefreshFn(obj) {
        if (obj.url != 'my') {
            let tabbarConf = this.data.tabbarConf
            if (tabbarConf[obj.url].num == obj.pageCount) {
                tabbarConf[obj.url].hasMore = false
            } else {
                tabbarConf[obj.url].hasMore = true
            }
            if (tabbarConf[obj.url].moreFlag == false) {
                tabbarConf[obj.url].hasMore = false
            }
            this.setData({
                tabbarConf
            })
        }
        wx.hideNavigationBarLoading()
        // 停止下拉动作
        wx.stopPullDownRefresh()
    },
    setLoadInfo(url) {
        let tabbarConf = this.data.tabbarConf
        tabbarConf[url].num = tabbarConf[url].num + 1
        tabbarConf[url].moreFlag = true
        this.setData({
            tabbarConf
        })
    },
    bind_dingwei: function () {
        if (!wx.getStorageSync('userInfo')) {
            wx.reLaunch({
                url: '/pages/login/index'
            })
            return;
        }
        wx.navigateTo({
            url: '/pages/dingwei/index',
        })
    },
    onPullDownRefresh: function () {
        this.indextoplist()
        let {
            activeUrl
        } = this.data
        // wx.showNavigationBarLoading()
        let tabbarConf = this.data.tabbarConf
        tabbarConf[activeUrl].num = 1
        this.setData({
            tabbarConf
        })

        this[activeUrl + 'GetInitData']()
       
        // this.indexGetInitData()
        // this.getInitData()
    },
    onReachBottom: function () {
        let {
            activeUrl
        } = this.data
        if (
            this.data.tabbarConf[activeUrl].hasMore &&
            this.data.tabbarConf[activeUrl].moreFlag
        ) {
            this.setLoadInfo(activeUrl)
            this[activeUrl + 'GetInitData']()
        }
    },
    // 公告详情
    goToAnnounce: function (e) {
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/announce/index?id=' + id,
        })
    },

    // 搜索部落 搜索话题
    goTotribe: function (e) {
        var nowText = e.currentTarget.dataset.text; //当前点击的索引
        wx.navigateTo({
            url: '/pages/homepagesearch/index?searchpage=' + 'interactive' + '&type=搜索话题',
        })
    }
})